<?php

namespace app\index\controller\v1\wechat;


use app\common\controller\WechatController;
use app\common\model\wechat\WechatTransfer;
use app\common\model\wechat\WechatUser;
use app\common\model\wechat\WechatUserWallet;
use app\common\model\wechat\WechatUserWalletLog;
use hiduoke\services\facade\WechatService;
use think\App;
use think\facade\Db;

/**
 * 钱包
 * @package app\index\controller\v1\wechat
 * User: liuhongbin
 * Date: 2021-07-08 10:37
 */
class Wallet extends WechatController
{
    /**
     * @var WechatUserWallet
     */
    private $model;
    /**
     * @var WechatUserWalletLog
     */
    private $WalletLog;
    /**
     * @var mixed|string
     */
    private $user;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new WechatUserWallet();
        $this->WalletLog = new WechatUserWalletLog();
        $this->user = WechatService::getUser();

    }

    public function index()
    {
        $this->assign('title', "用户钱包");
        return $this->fetch("index");
    }

    /**
     * 获取钱包信息
     * @return \think\response\Json
     */
    public function getUserWallet()
    {
        $wallet = $this->model->getUserWallet();
        $wallet['all_money'] = $wallet['money'] + $wallet['frozen_money'];
        return $this->success('ok', $wallet);
    }

    /**
     * 获取用户的提现记录
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserWalletLog()
    {
        $page = input('page', 1);
        $size = input('size', 10);
        $where = ['uid' => $this->user['id']];
        $list = $this->WalletLog->where($where)->limit($size)->order('id DESC')->page($page)->select();
        foreach ($list as $key => $value) {
            $list[$key]['count_money'] = sprintf('%.2f', $value['money'] + $value['frozen_money']);
            $list[$key]['after_count_money'] = sprintf('%.2f', $value['after_money'] + $value['after_frozen_money']);
            $list[$key]['change_desc'] = $value['change_desc'] ?: '默认备注';
        }
        $count = $this->WalletLog->where($where)->count();
        return $this->success($count, $list);
    }

    /**
     * 获取用户的提现列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserTransfer()
    {
        $page = input('page', 1);
        $size = input('size', 10);
        $where = ['openid' => $this->user['openid']];
        $WechatTransfer = new WechatTransfer();
        $list = $WechatTransfer->where($where)->limit($size)->order('id DESC')->page($page)->select();
        foreach ($list as $key => $value) {
            $list[$key]['money'] = sprintf('%.2f', $value['amount'] / 100);
            $list[$key]['desc'] = $value['desc'] ?: '默认备注';
        }
        $count = $WechatTransfer->where($where)->count();
        return $this->success($count, $list);
    }

    /**
     * 用户提现操作
     * @return \think\response\Json
     */
    public function userMoneyWithdrawal()
    {
        $money = input('money', 0);
        if ($money <= 0.3) {
            return $this->error('提现金额不能为空，且不能小于0.3元');
        }
        $wallet = $this->model->getUserWallet();
        $surplus_money = $wallet->money - $money;
        if ($surplus_money < 0) {
            return $this->error('余额不足');
        }
//
//        Db::transaction(function () use ($money, $wallet) {
//            $wallet->changeMoney(-$money, '余额提现');
//            $res = WechatService::transfer($money, '活动红包');
//            if (!WechatService::checkResult($res)) {
//                abort($this->error('提现失败' . $res['return_msg'], [], -1));
//            }
//        });

        // 启动事务
        Db::startTrans();
        try {
            $wallet->changeMoney(-$money, '余额提现');
            $res = WechatService::transfer($money, '活动红包');
            if (!WechatService::checkResult($res)) {
                Db::rollback();
                return $this->error("提现失败" . $res['return_msg']);
//                abort($this->error('提现失败' . $res['return_msg'], [], -1));
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }

        return $this->success('申请提现成功', $surplus_money);
    }
}
